package com.zkflzl.mianshi.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkflzl.mianshi.common.BaseResponse;
import com.zkflzl.mianshi.common.DeleteRequest;
import com.zkflzl.mianshi.common.ErrorCode;
import com.zkflzl.mianshi.common.ResultUtils;
import com.zkflzl.mianshi.constant.UserConstant;
import com.zkflzl.mianshi.exception.BusinessException;
import com.zkflzl.mianshi.exception.ThrowUtils;
import com.zkflzl.mianshi.model.dto.question.QuestionListRequest;
import com.zkflzl.mianshi.model.dto.user.*;
import com.zkflzl.mianshi.model.entity.User;
import com.zkflzl.mianshi.model.vo.LoginUserVO;
import com.zkflzl.mianshi.model.vo.QuestionListVO;
import com.zkflzl.mianshi.model.vo.UserVO;
import com.zkflzl.mianshi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import static com.zkflzl.mianshi.service.impl.UserServiceImpl.SALT;

/**
 * 用户接口
 *
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
//@Api(tags = "用户接口")
public class UserController {

    @Resource
    private UserService userService;

    // region 登录相关

    /**
     * 用户来获取随机验证码
     *
     * @param request
     * @return
     * @throws IOException
     */
    @GetMapping("/getCode")
//    @ApiOperation("获取随机验证码(以图片的形式展示)")
    public BaseResponse<String> getCode(HttpServletRequest request) {
        // 获取图片验证码
        String encodedImage = userService.getCodeResp(request);

        // 返回Base64编码的图片
        return ResultUtils.success(encodedImage);
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest,
                                               HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        LoginUserVO loginUserVO = userService.userLogin(userLoginRequest, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAddRequest.getUserAccount());
        long count = userService.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    // 修改用户密码
    @PostMapping("/change/password")
    public BaseResponse<Boolean> changePassword(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                                HttpServletRequest request) {
        return userService.changePassword(userUpdateMyRequest, request);
    }


    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
                                            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        // 管理员账号权限暂无法修改
        if (StringUtils.isNotBlank(userUpdateRequest.getUserRole())) {
            if (Objects.equals(user.getUserRole(), UserConstant.ADMIN_ROLE)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 判断账号名称是否已存在
        if (StringUtils.isNotBlank(userUpdateRequest.getUserAccount())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userUpdateRequest.getUserAccount())
                    .ne("id", userUpdateRequest.getId());
            long count = userService.count(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
        }

        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    //@ApiOperation("根据 id 获取包装类")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    //@ApiOperation("分页获取用户列表（仅管理员）")
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                   HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    //@ApiOperation("分页获取用户封装列表")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                       HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    //@ApiOperation("更新个人信息")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 添加用户签到记录
     *
     * @param request
     * @return 当前是否已签到成功
     */
    @PostMapping("/add/sign_in")
    //@ApiOperation("添加用户签到记录")
    public BaseResponse<Boolean> addUserSignIn(HttpServletRequest request) {
        // 必须要登录才能签到
        User loginUser = userService.getLoginUser(request);
        boolean result = userService.addUserSignIn(loginUser.getId());
        return ResultUtils.success(result);
    }

    /**
     * 获取用户签到记录
     *
     * @param year    年份（为空表示当前年份）
     * @param request
     * @return 签到记录映射
     */
    @GetMapping("/get/sign_in")
    //@ApiOperation("获取用户签到记录")
    public BaseResponse<List<Integer>> getUserSignInRecord(Integer year, HttpServletRequest request) {
        // 必须要登录才能获取
        User loginUser = userService.getLoginUser(request);
        List<Integer> userSignInRecord = userService.getUserSignInRecord(loginUser.getId(), year);
        return ResultUtils.success(userSignInRecord);
    }

    // 获取用户喜欢列表
    @PostMapping("/question/thumb/list")
    //@ApiOperation("获取用户喜欢列表")
    public BaseResponse<Page<QuestionListVO>> getQuestionUserThumbList(
            @RequestBody QuestionListRequest questionListRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Page<QuestionListVO> postVOList = userService.getQuestionUserThumbList(questionListRequest, loginUser.getId());
        return ResultUtils.success(postVOList);
    }

    // 获取用户收藏列表
    @PostMapping("/question/favor/list")
    //@ApiOperation("获取用户收藏列表")
    public BaseResponse<Page<QuestionListVO>> getQuestionUserFavorList(
            @RequestBody QuestionListRequest questionListRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Page<QuestionListVO> postVOList = userService.getQuestionUserFavorList(questionListRequest, loginUser.getId());
        return ResultUtils.success(postVOList);
    }

    /**
     * 上传头像图片并返回可访问地址
     */
    //@ApiOperation("上传头像图片并返回可访问地址")
    @PostMapping("/upload/avatar")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<String> uploadAvatar(@RequestParam("img") MultipartFile file,
                                             @RequestParam(required = false) Long userId,
                                             HttpServletRequest request) {
        ThrowUtils.throwIf(file == null, ErrorCode.PARAMS_ERROR);
        return userService.uploadAvatar(file, userId, request);
    }

    /**
     * 删除用户头像
     */
    @PostMapping("/del/avatar")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<String> delAvatar(@RequestParam String userAvatar, @RequestParam(required = false) Long userId,
                                          HttpServletRequest request) {
        ThrowUtils.throwIf(StringUtils.isBlank(userAvatar), ErrorCode.PARAMS_ERROR);
        return userService.delAvatar(userAvatar, userId, request);
    }

}
